package edu.nanyang.controller;

import com.github.pagehelper.PageInfo;
import edu.nanyang.domain.AcademyInfo;
import edu.nanyang.domain.AdminInfo;
import edu.nanyang.domain.MajorInfo;
import edu.nanyang.service.AcademyInfoService;
import edu.nanyang.service.MajorInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/admin/major")
public class MajorInfoController extends BaseController{
    @Resource
    private MajorInfoService majorInfoService;
    @Resource
    private AcademyInfoService academyInfoService;

    @GetMapping("/search")
    public String search(int page){
        PageInfo<MajorInfo> pageInfo= majorInfoService.search(page,2);
        request.setAttribute("page_vo",pageInfo);
        return "admin/major/major_list";
    }

    @GetMapping("/addpage")
    public String addPage(){
        List<AcademyInfo> academyInfoList=academyInfoService.findAll();
        request.setAttribute("academy_list",academyInfoList);
        return "admin/major/major_add";
    }

    @GetMapping("updatepage")
    public String updatePage(int id){
        MajorInfo majorInfo=majorInfoService.getById(id);
        request.setAttribute("major_info",majorInfo);
        List<AcademyInfo> academyInfoList=academyInfoService.findAll();
        request.setAttribute("academy_list",academyInfoList);
        return "admin/major/major_edit";
    }

    @PostMapping("/updatesave")
    public String updateSave(MajorInfo majorInfo) {
        int result = majorInfoService.update(majorInfo);
        String tipInfo = "修改成功！";
        if (result < 0) {
            tipInfo = "修改失败！";
        }
        request.setAttribute("tip_info", tipInfo);
        //请求转发
        return "result";
    }


    @PostMapping("/addsave")
    public String addSave(MajorInfo majorInfo) {
        HttpSession session=request.getSession();
        AdminInfo adminInfo=(AdminInfo) session.getAttribute("login_admin");
        majorInfo.setCreator(adminInfo.getId());

        int result = majorInfoService.add(majorInfo);
        String tipInfo = "添加成功！";
        if (result < 0) {
            tipInfo = "添加失败！";
        }
        request.setAttribute("tip_info", tipInfo);
        //请求转发
        return "result";
    }

    @GetMapping("/delete")
    public String delete(int id) throws ServletException, IOException {
        int result = majorInfoService.delete(id);
        String tipInfo = "删除成功！";
        if (result < 0) {
            tipInfo = "删除失败！";
        }
        request.setAttribute("tip_info", tipInfo);
        //请求转发
        return "forward:search?page=1";
    }


}
